#include "ble_rev_main.h"
#include "debug_config.h"
#include "local_main.h"
#include "application.h"
#include <stdio.h>

#define GET_UTC_TIME_TIME   (100)   //请求网络同步时间
#define FPTADD_TIMEOUT_TIME (10000) //指纹添加的超时时间
#define NFCADD_TIMEOUT_TIME (10000) //NFC添加的超时时间

uint8_t Menu_Exit_Managemode(void);

//static TimerHandle_stu_t bleActiveTimer = NULL;       //绑定过程的2分钟，不休眠
//static uint8_t bleConnectSta = 0;
uint8_t attribute_test[] = {0x0A, 0x00, 0x00, 0x56, 0xFF, 0x00, 
                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFC, 0x61, 0x79, 0xCE, 0x98, 0x33, 0x31, 0x2E, 0x30, 0x30, 0x2E, 0x30,
	                        0x30, 0x00, 0x00, 0x00, 0x31, 0x2E, 0x30, 0x30, 0x2E, 0x32, 0x36, 0x00, 0x00, 0x00, 0x48, 0x4B, 0x30, 0x31, 0x00, 0x00,
	                        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04};//HK01 
static uint32_t random_code_global = 0;
static uint16_t Lock_seq = 0;
static uint32_t g_event_id = 10000;//TODO:暂时使用自加的id
static FlagStatus appDelCardFlag = RESET;	// app删除卡片标志
static TimerHandle_stu_t getutctime_Timer = NULL;    //请求网络同步时间的定时器
static TimerHandle_stu_t fptadd_timeout_Timer = NULL;//指纹添加的超时定时器
static TimerHandle_stu_t nfcadd_timeout_Timer = NULL;//nfc添加的超时定时器
Ble_enroll_finer_ack_stu_t Ble_enrollfiner_ack_temp = {0};
static void Add_Finger_Timeout_Callback(TimerHandle_stu_t xTimer);
static void Add_Nfc_Timeout_Callback(TimerHandle_stu_t xTimer);
static void FuncBle_general_send_Handle(uint16_t vts, uint16_t cmd, uint8_t payloadLen, uint8_t *payload);


/**
 * @brief 发送命令字
 *
 * @param [in] len
 * @param [in] pData
 * @return uint8_t
 *
 * @note
 */
static uint8_t BleRevMain_send_Cmd(uint8_t *pData, uint8_t len)
{
    BleCallbackMsg_t msg = {
        .source = BLE_MSG_CMD,
        .cmd = 0,
        .ret = 0,
        .len = len,
        .pData = {0},
    };
    if (len <= sizeof(msg.pData))
    {
        memcpy(msg.pData, pData, len);
    }
    else
    {
        FUNC_BLE_LOG_I("Send cmd len error");
        return 0;
    }
    FUNC_BLE_LOG_HEX("Ble Send cmd data:", msg.pData, len);

    Ble_SendDataToBle(&msg, len);
}


/**
 * @brief 通用应答
 *
 *
 * @note
 */
//static void FuncBle_lkm3_general_ack_Handle(uint32_t cmd, uint8_t result)
//{
//    Ble_genaral_ack_t ack = {0};
//    uint16_t massageType = (uint16_t)cmd;

//    (result == EVIDENCE_ACK_SUCCESS) ? (ack.result = OSAL_SWAP16(CMD_GENERAL_SUCCESS)) : (ack.result = OSAL_SWAP16(CMD_GENERAL_ERROR));

//    ack.massageType = OSAL_SWAP16(massageType);
//    BleRevMain_send_Cmd((uint8_t *)&ack, sizeof(ack));
//}

/**
 * @brief 获取随机码
 *
 *
 * @note
 */
static void FuncBle_get_randcode(int8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t randcode_Ack = {0};
    Ble_genaral_rev_t *general_recv = Data;//
    uint32_t rand_get = 0;
    uint16_t vts_temp = 0;//
    FUNC_BLE_LOG_D("len:%d",len);

    rand_get = (uint32_t)rand();
    randcode_Ack.dataLen = 0x0010;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = 0x00000001;//TODO: 是否一直为01 

    FUNC_BLE_LOG_D("general_recv->vts:%04x",general_recv->vts);
    FUNC_BLE_LOG_D("general_recv->vts low8:%02x",(uint8_t)general_recv->vts);
    FUNC_BLE_LOG_D("general_recv->vts high8:%02x",(uint8_t)(general_recv->vts >> 8));
    vts_temp = (general_recv->vts & 0xFF00) | ((uint16_t)((uint8_t)general_recv->vts & 0xF3));//
    randcode_Ack.Payload.vts = vts_temp;//
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_GET_RAND_CODE);

    random_code_global = rand_get;
    memcpy(randcode_Ack.Payload.dataBuf, &rand_get, sizeof(rand_get));
    FUNC_BLE_LOG_D("rand_get:%d",rand_get);
    BleRevMain_send_Cmd((uint8_t *)&randcode_Ack.dataLen, randcode_Ack.dataLen);
}

/**
 * @brief 绑定指令
 *
 *
 * @note
 */
static void FuncBle_Bind(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
   //uint8_t i = 0;
   uint16_t result = 0x0000;//0:成功  1:失败
   uint8_t password[8] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    //FUNC_BLE_LOG_HEX("FuncBle_Bind Data:", Data, len);
    //FUNC_BLE_LOG_HEX("FuncBle_Bind tempBuff:", tempBuff, len);

    randcode_Ack.dataLen = 0x0016;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);//

    // seq = packet.pData[10] & 0x03;
    // bind_test[10] = ((bind_test[10] & 0xFC) | seq);
    // bind_test[11] = packet.pData[11];
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_DEVICE_BIND);

    memcpy(randcode_Ack.Payload.dataBuf, &result, sizeof(result));
    memcpy(&randcode_Ack.Payload.dataBuf[2], password, sizeof(password));

    FUNC_BLE_LOG_D("sizeof(result):%d",sizeof(result));
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);//
    //FUNC_BLE_LOG_HEX("FuncBle_Bind:", &randcode_Ack,randcode_Ack.dataLen); //OSAL_SWAP16(randcode_Ack.dataLen)
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);//sizeof(randcode_Ack)+4 OSAL_SWAP16(randcode_Ack.dataLen)

    Ble_Encryptionflag(1);
}

/**
 * @brief 密钥校验指令: 0x9062
 *
 *
 * @note
 */
static void FuncBle_KeyCheck(int8_t len, uint8_t *Data)
{
    BleAckPacket_stu_t randcode_Ack = {0};
    uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
    uint8_t password[8] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};//TODO：后续看是否要更新固定密码 
    uint16_t result = 0x0001;//0:成功  1:失败
    uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    memcpy(tempBuff, Data, len);



    randcode_Ack.dataLen = 0x000E;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;//

    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//<<<<<
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);//

    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_KEY_CHECK);

    if (memcmp(password, &tempBuff[4], 8) == 0)
    {
        result = 0X0000;
        FUNC_BLE_LOG_D("KeyCheck OK");
    }
    memcpy(randcode_Ack.Payload.dataBuf, &result, sizeof(result));

    FUNC_BLE_LOG_D("sizeof(result):%d",sizeof(result));
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);
}

/**
 * @brief 查询门锁产品信息
 *
 *
 * @note
 */
static void FuncBle_Get_Product_Info(int8_t len, uint8_t *Data)
{
    BleAckPacket_stu_t randcode_Ack = {0};
    uint8_t tempBuff[40] = {0}; 
    uint8_t SN[32] = DEFAULT_SN; //TODO: 从厂测写入NV,再从NV读取出来
    uint8_t product_id[16] = PRODUCT_ID;
    uint8_t aeskey[32] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};//密钥 TODO: 统一放在一个地方


    uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);

    memcpy(tempBuff, Data, len);
    randcode_Ack.dataLen = 0x005C;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;

    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_GET_PRODUCT_INFO);

    memcpy(randcode_Ack.Payload.dataBuf, SN, sizeof(SN));
    memcpy(&randcode_Ack.Payload.dataBuf[sizeof(SN)], aeskey, sizeof(aeskey));
    memcpy(&randcode_Ack.Payload.dataBuf[sizeof(SN) + sizeof(aeskey)], product_id, sizeof(product_id));

    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);

}

/**
 * @brief 获取门锁属性
 *
 *
 * @note LOCK_ALL_ATTR
 */
static void FuncBle_Get_All_Attr(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
   uint8_t blemac[6];
   //uint8_t i = 0;
   //uint16_t result = 0x0000;//0:成功  1:失败
   //uint8_t password[8] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    //FUNC_BLE_LOG_HEX("FuncBle_Get_All_Attr Data:", Data, len);
    //FUNC_BLE_LOG_HEX("FuncBle_Bind tempBuff:", tempBuff, len);

    randcode_Ack.dataLen = 0x0041;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);//

    // seq = packet.pData[10] & 0x03;
    // bind_test[10] = ((bind_test[10] & 0xFC) | seq);
    // bind_test[11] = packet.pData[11];
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_GET_LOCK_ALL_ATTR);

    #if 1
    OSAL_NvRead(SYS_OFFSET(bleMacAddr), blemac, sizeof(blemac));
    memcpy(&attribute_test[14], blemac, sizeof(blemac));

    #endif 
    memcpy(randcode_Ack.Payload.dataBuf, attribute_test, sizeof(attribute_test));

    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);//
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);//sizeof(randcode_Ack)+4 OSAL_SWAP16(randcode_Ack.dataLen)
}

/**
 * @brief 开锁
 *
 *
 * @note
 */
static void FuncBle_Unlock(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
   uint16_t result = 0x0000;//0:成功  1:失败
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    FUNC_BLE_LOG_HEX("FuncBle_Unlock:", Data, len);
    //FUNC_BLE_LOG_HEX("FuncBle_Bind tempBuff:", tempBuff, len);

    randcode_Ack.dataLen = 0x000E;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);//

    // seq = packet.pData[10] & 0x03;
    // bind_test[10] = ((bind_test[10] & 0xFC) | seq);
    // bind_test[11] = packet.pData[11];
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_UNLOCK);

    memcpy(randcode_Ack.Payload.dataBuf, &result, sizeof(result));
   
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);//
    FUNC_BLE_LOG_HEX("FuncBle_Unlock:", &randcode_Ack,randcode_Ack.dataLen); //OSAL_SWAP16(randcode_Ack.dataLen)
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);//sizeof(randcode_Ack)+4 OSAL_SWAP16(randcode_Ack.dataLen)

    Local_LockControl(USERS_TYPE_BLE, 0xFF, LOCK_CTRL_UNLOCK);
}

/**
 * @brief 关锁
 *
 *
 * @note
 */
static void FuncBle_Locked(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
   uint16_t result = 0x0000;//0:成功  1:失败
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    FUNC_BLE_LOG_HEX("FuncBle_Locked:", Data, len);
    //FUNC_BLE_LOG_HEX("FuncBle_Bind tempBuff:", tempBuff, len);

    randcode_Ack.dataLen = 0x000E;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//<<<<<
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);//

    // seq = packet.pData[10] & 0x03;
    // bind_test[10] = ((bind_test[10] & 0xFC) | seq);
    // bind_test[11] = packet.pData[11];
    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_LOCKED);

    memcpy(randcode_Ack.Payload.dataBuf, &result, sizeof(result));
   
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);//
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);//sizeof(randcode_Ack)+4 OSAL_SWAP16(randcode_Ack.dataLen)

    Local_LockControl(LOCKED_ROMOTE, 0xFF, LOCK_CTRL_LOCKED);
}

/**
 * @brief 获取门锁状态
 *
 *
 * @note
 */
static void FuncBle_Get_Lock_Status(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};// BLE_COMP_BUFFER_SIZE
   uint8_t result = 0x00;//0:开锁  1:关锁
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
    FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    FUNC_BLE_LOG_HEX("FuncBle_Get_Lock_Status:", Data, len);

    randcode_Ack.dataLen = 0x000D;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);

    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_GET_LOCK_STATUS);

     //获取门锁状态
    result = SYS_CALL(local_LockGetLockStatus);
    FUNC_BLE_LOG_D("lock_state:%d\n", result);
    if (result == LOCK_ACTION_LOCKED || result == LOCK_ACTION_LOCKED_MACH) //上锁成功
    {
        result = 1;
    }
    else if (result == LOCK_ACTION_UNLOCK_NO_BACK || result == LOCK_ACTION_UNLOCK || result == LOCK_ACTION_UNLOCK_MACH) //开锁成功
    {
        result = 0;
    }
    else
    {
        result = 2;  // 异常 
    }
    FUNC_BLE_LOG_D("result:%d\n", result);

    memcpy(randcode_Ack.Payload.dataBuf, &result, sizeof(result));
   
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);//
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);

}

/**
 * @brief 设置锁的音量
 *
 *
 * @note
 */
static void FuncBle_Set_Volume(int8_t len, uint8_t *Data)
{
   BleAckPacket_stu_t randcode_Ack = {0};
   uint8_t tempBuff[40] = {0};
   int16_t  errno = 0;
   uint8_t volume = 0;   //语音导航音量  
   uint8_t db_volume = 0;//门铃音量:没有用到
   uint8_t voice = 0;
   uint16_t seq = 0;
   uint16_t vts_temp = 0;
   FUNC_BLE_LOG_D("len:%d",len);
    
    memcpy(tempBuff, Data, len);

    FUNC_BLE_LOG_HEX("FuncBle_Set_Volume:", Data, len);

    randcode_Ack.dataLen = 0x0010;
    randcode_Ack.dst_addr = APP;
    randcode_Ack.src_addr = LKMD;
    randcode_Ack.random_code = random_code_global;
    
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];
    randcode_Ack.Payload.vts = OSAL_SWAP16(vts_temp);

    randcode_Ack.Payload.cmd = OSAL_SWAP16(BLE_SET_VOLUME);

    volume = tempBuff[4];
    db_volume = tempBuff[5];


    //语音导航音量 1 – 静音， 2 – 低， 3 – 中， 4 – 高
    switch (volume)
    {
        case 1:
            Audio_SetMuteMode(SET);
            break;
        case 2:
            voice = 60;
            Audio_SetVolume(voice);
            Audio_SetMuteMode(RESET);
            break;
        case 3:
            voice = 80;
            Audio_SetVolume(voice);
            Audio_SetMuteMode(RESET);
            break;
        case 4:
            voice = 100;
            Audio_SetVolume(voice);
            Audio_SetMuteMode(RESET);
            break;
        default:
                //errno = 1;
            break;
    }

    FUNC_BLE_LOG_D("volume:%d\n", volume);
    memcpy(randcode_Ack.Payload.dataBuf, &errno, sizeof(errno));
    memcpy(&randcode_Ack.Payload.dataBuf[2], &volume, sizeof(volume));
    memcpy(&randcode_Ack.Payload.dataBuf[3], &db_volume, sizeof(db_volume));
    FUNC_BLE_LOG_D("randcode_Ack.Payload.vts:%x",randcode_Ack.Payload.vts);
    BleRevMain_send_Cmd(&randcode_Ack, randcode_Ack.dataLen);
}

/**
 * @brief 设置管理员密码
 *
 *
 * @note
 */
static void FuncBle_Set_Admin_Pwd(int8_t len, uint8_t *Data)
{
    BleAckPacket_stu_t AdminPwdSetAck_Send = {0};
    Ble_AdminPwdSet_stu_t *AdminPwdSet = (Ble_AdminPwdSet_stu_t *)Data;
    Ble_AdminPwdSet_ack_stu_t *AdminPwdSetAck = NULL;

    uint8_t tempBuff[50] = {0};//-- 可以去掉
    uint8_t pwd[PWD_LEN_MAX] = {0};
    uint16_t vts_temp = 0;
    uint8_t pwd_length = 0;
    uint8_t keyType = 0, keyNum = 0, keyAttr = 0xFF, ackBuffLen = 0;//  keyAttr
    uint8_t *pAckBuff = NULL;
    ErrorStatus adminPwdEasyFlag = SYS_CALL(Users_AdminPwdIsEasy);

    ackBuffLen = sizeof(Ble_AdminPwdSet_ack_stu_t);
    pAckBuff = OSAL_Malloc(ackBuffLen);
    if (pAckBuff == NULL)
    {
        FUNC_BLE_LOG_W("malloc error");
        return;
    }

    memcpy(tempBuff, Data, len);//可以去掉
    memset(pAckBuff,0,ackBuffLen);
    AdminPwdSetAck = (Ble_AdminPwdSet_ack_stu_t *)pAckBuff;
    FUNC_BLE_LOG_D("len:%d",len);
    FUNC_BLE_LOG_HEX("FuncBle_Set_Admin_Pwd:", Data, len);

    AdminPwdSetAck_Send.dataLen =  ackBuffLen + 12;//0x003F; 
    AdminPwdSetAck_Send.dst_addr = APP;
    AdminPwdSetAck_Send.src_addr = LKMD;
    AdminPwdSetAck_Send.random_code = random_code_global; //

    // FUNC_BLE_LOG_D("tempBuff[0]:%02x",tempBuff[0]);// 
    // FUNC_BLE_LOG_D("tempBuff[1]:%02x",tempBuff[1]);// 
    // FUNC_BLE_LOG_D("keySet->vts:%04x",keySet->vts);// tempBuff[0) 是  keySet->vts 的低8 位？
    // FUNC_BLE_LOG_D("keySet->vts low8:%02x",(uint8_t)keySet->vts);
    // FUNC_BLE_LOG_D("keySet->vts high8:%02x",(uint8_t)(keySet->vts >> 8));
    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//keySet->vts,   tempBuff[0] tempBuff[1]  都打印出来
    AdminPwdSetAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    AdminPwdSetAck_Send.Payload.cmd = OSAL_SWAP16(BLE_SET_ADMIN_PWD);

    for(uint8_t i = 0; i < sizeof(pwd); i++)
    {
        if(AdminPwdSet->passwd[i] != 0)
        {
            pwd_length++;
        }
        else
        {
            break;
        }
    }
    FUNC_BLE_LOG_D("pwd_length:%d",pwd_length);

    memcpy(pwd, AdminPwdSet->passwd, pwd_length);
    ASCII_TO_INT(pwd, pwd_length);

    keyType = USERS_TYPE_PWD;
    //keyNum = SYS_CALL(Users_GetValidId, keyType); //
    //FUNC_BLE_LOG_D("keyNum:%d",keyNum);
    keyNum = USERS_ID_ADMIN;//

    //FUNC_BLE_LOG_HEX("pwd:", pwd, pwd_length);//003
    // 管理密码为 简单密码，才可以设置管理密码 
    if(adminPwdEasyFlag == SUCCESS)
    {
        UsersAddRes_enum_t AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, RESET);  
        if (AddRes == ADD_ONCE_OK)
        {
            FUNC_BLE_LOG_D("Add pwd once OK!");
            AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, SET);
        }
        switch (AddRes)
        {
            case ADD_SUCCESS:
                // if (keyAttr == USERS_ATTR_PLOY || keyAttr == USERS_ATTR_WEEK)
                // {

                // }
                // else
                //{
                    FUNC_BLE_LOG_D("Add pwd Success, attr = %d", keyAttr);
                    AdminPwdSetAck->error_code = ERRNO_OK;
                    if(keyNum == USERS_ID_ADMIN)
                    {
                        Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_MODIFY, keyNum);
                    }
                    // else
                    // {
                    //     Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_ADD, keyNum);
                    // }
                //}
                break;
            
            case ADD_ERR_TOO_SIMPLE:
                AdminPwdSetAck->error_code = ERRNO_PWD_ILLEGAL;// OSAL_SWAP16(ERRNO_PWD_ILLEGAL);
                break;
            case ADD_ERR_EXISTS:
                AdminPwdSetAck->error_code = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_RANGE:
                AdminPwdSetAck->error_code = ERRNO_PWD_ILLEGAL;
                break;
            case ADD_ERR_CARD_EXISTS:
                AdminPwdSetAck->error_code = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_KEYS_LIB_IS_FULL:
                AdminPwdSetAck->error_code = ERRNO_PWD_FULL;
                break;
            default:
                AdminPwdSetAck->error_code = ERRNO_UNKNOWN;
                break;
        }
    }
    else
    {
        AdminPwdSetAck->error_code = ERRNO_PWD_FULL; //管理密码已经设置过了 
    }
    
    AdminPwdSetAck->id = 0;//OSAL_SWAP16(USERS_ID_ADMIN); //TODO: 管理密码是否要上报ID为0;  是否要取反

    memcpy(AdminPwdSetAck_Send.Payload.dataBuf, &AdminPwdSetAck->error_code, sizeof(Ble_AdminPwdSet_ack_stu_t)); 
    FUNC_BLE_LOG_D("sizeof(Ble_AdminPwdSet_ack_stu_t):%d",sizeof(Ble_AdminPwdSet_ack_stu_t));//
    BleRevMain_send_Cmd(&AdminPwdSetAck_Send, AdminPwdSetAck_Send.dataLen);
    OSAL_Free(pAckBuff);
}

/**
 * @brief 修改管理员密码
 *
 *
 * @note
 */
static void FuncBle_Change_Admin_Pwd(int8_t len, uint8_t *Data)
{
    BleAckPacket_stu_t AdminPwdChangeAck_Send = {0};
    Ble_AdminPwdChange_stu_t *AdminPwdChange = (Ble_AdminPwdChange_stu_t *)Data;
    uint16_t result = 0;// 0 - 成功 , 1 - 失败, 2-旧管理员密码错误，3-新密码格式错误
    uint8_t tempBuff[50] = {0};//-- 可以去掉 44
    uint8_t pwd_old[PWD_LEN_MAX] = {0};
    uint8_t pwd_new[PWD_LEN_MAX] = {0};
    uint16_t vts_temp = 0;
    uint8_t pwd_old_length = 0;
    uint8_t pwd_new_length = 0;
    uint8_t keyNum = 0, keyAttr = 0xFF;//  keyAttr
    //ErrorStatus adminPwdEasyFlag = SYS_CALL(Users_AdminPwdIsEasy);

    memcpy(tempBuff, Data, len);//可以去掉
    FUNC_BLE_LOG_D("len:%d",len);
    FUNC_BLE_LOG_HEX("FuncBle_Change_Admin_Pwd:", Data, len);

    AdminPwdChangeAck_Send.dataLen =  16;// 4 + 12
    AdminPwdChangeAck_Send.dst_addr = APP;
    AdminPwdChangeAck_Send.src_addr = LKMD;
    AdminPwdChangeAck_Send.random_code = random_code_global; //

    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//keySet->vts,   tempBuff[0] tempBuff[1]  都打印出来
    AdminPwdChangeAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    AdminPwdChangeAck_Send.Payload.cmd = OSAL_SWAP16(BLE_CHANGE_ADMIN_PWD);

    for(uint8_t i = 0; i < sizeof(pwd_old); i++) //  老的密码要验证通过，新的密码才能修改成功
    {
        if(AdminPwdChange->old_password[i] != 0)
        {
            pwd_old_length++;
        }
        else
        {
            break;
        }
    }
    FUNC_BLE_LOG_D("pwd_old_length:%d",pwd_old_length);
    memcpy(pwd_old, AdminPwdChange->old_password, pwd_old_length);
    ASCII_TO_INT(pwd_old, pwd_old_length);

    for(uint8_t i = 0; i < sizeof(pwd_new); i++)
    {
        if(AdminPwdChange->new_password[i] != 0)
        {
            pwd_new_length++;
        }
        else
        {
            break;
        }
    }
    FUNC_BLE_LOG_D("pwd_new_length:%d",pwd_new_length);
    memcpy(pwd_new, AdminPwdChange->new_password, pwd_new_length);
    ASCII_TO_INT(pwd_new, pwd_new_length);

    // TODO: 管理密码为 非简单密码， 才可以 修改管理密码 ?
	keyNum = SYS_CALL(Users_Verify, pwd_old, pwd_old_length, 0, USERS_TYPE_PWD, 2, 0);
    if ( keyNum == USERS_ID_ADMIN ) //老的密码要验证通过，新的密码才能修改成功
    { 
        UsersAddRes_enum_t AddRes = SYS_CALL(Users_Add, USERS_TYPE_PWD, keyNum, pwd_new, pwd_new_length, keyAttr, RESET); 
        FUNC_BLE_LOG_D("AddRes1:%d", AddRes);
        if (AddRes == ADD_ONCE_OK)
        {
            AddRes = SYS_CALL(Users_Add, USERS_TYPE_PWD, keyNum, pwd_new, pwd_new_length, keyAttr, SET);
            FUNC_BLE_LOG_D("AddRes2:%d", AddRes);
        }
        switch (AddRes)
        {
            case ADD_SUCCESS:
                    result = SET_SUCCESS;
                    Local_LockSaveRecord(EVENT_TYPE_PROGRAM, USERS_TYPE_PWD, EVENT_CODE_MODIFY, keyNum);
                break;
            
            case ADD_ERR_TOO_SIMPLE:
                result = NEW_ADMINPWD_FORMAT_ERR;
                break;
            case ADD_ERR_EXISTS:
                result = NEW_ADMINPWD_FORMAT_ERR;// 
                break;
            case ADD_ERR_RANGE:
                result = NEW_ADMINPWD_FORMAT_ERR;
                break;
            case ADD_ERR_KEYS_LIB_IS_FULL:
                result = SET_FAILED;
                break;
            default:
                result = SET_FAILED;
                break;
        }
    }
    else
    {
        result = OLD_ADMINPWD_ERR;//是否要倒序？ OSAL_SWAP16(OLD_ADMINPWD_ERR)
        FUNC_BLE_LOG_D("old admin verify failed"); 
    }
     
    memcpy(AdminPwdChangeAck_Send.Payload.dataBuf, &result, sizeof(result));
    BleRevMain_send_Cmd(&AdminPwdChangeAck_Send, AdminPwdChangeAck_Send.dataLen);
}

/**
 * @brief 远程添加本地密码
 *
 *
 * @note
 */
static void FuncBle_Add_Local_Pwd(int8_t len, uint8_t *Data)
{
    BleAckPacket_stu_t KeySetAck_Send = {0};
    Ble_keySet_stu_t *keySet = (Ble_keySet_stu_t *)Data;
    Ble_keySet_ack_stu_t *keySetAck = NULL;
    UserAttrPloy_stu_t AttrPloy;

    uint8_t tempBuff[50] = {0};//-- 可以去掉
    uint8_t pwd[PWD_LEN_MAX] = {0};
    uint16_t vts_temp = 0;
    uint8_t pwd_length = 0;
    uint8_t keyType = 0, keyNum = 0, keyAttr = 0xFF, ackBuffLen = 0;//  keyAttr
    uint8_t *pAckBuff = NULL;

    memset(&AttrPloy, 0, sizeof(UserAttrPloy_stu_t));
    ackBuffLen = sizeof(Ble_keySet_ack_stu_t); 
    pAckBuff = OSAL_Malloc(ackBuffLen);
    if (pAckBuff == NULL)
    {
        FUNC_BLE_LOG_W("malloc error");
        return;
    }

    memcpy(tempBuff, Data, len);//可以去掉
    memset(pAckBuff,0,ackBuffLen);
    keySetAck = (Ble_keySet_ack_stu_t *)pAckBuff;

    FUNC_BLE_LOG_D("len:%d",len);
    FUNC_BLE_LOG_HEX("FuncBle_Add_Local_Pwd:", Data, len);

    //FUNC_BLE_LOG_D("sizeof(Ble_keySet_stu_t):%d",sizeof(Ble_keySet_stu_t));
    KeySetAck_Send.dataLen =  ackBuffLen + 12;//0x003F; 
    KeySetAck_Send.dst_addr = APP;
    KeySetAck_Send.src_addr = LKMD;
    KeySetAck_Send.random_code = random_code_global; //

    vts_temp = (( (uint16_t)(tempBuff[0] & 0xF3) ) << 8 ) + tempBuff[1];//keySet->vts,   tempBuff[0] tempBuff[1]  都打印出来
    KeySetAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    KeySetAck_Send.Payload.cmd = OSAL_SWAP16(BLE_ADD_LOCAL_PWD);

    FUNC_BLE_LOG_D("keySet->pwd_type:%d", keySet->pwd_type);

    if(keySet->pwd_type == 0)
    {
        //添加长期密码 
        for(uint8_t i = 0; i < sizeof(pwd); i++)
        {
            if(keySet->passwd[i] != 0)
            {
                pwd_length++;
            }
            else
            {
                break;
            }
        }
        FUNC_BLE_LOG_D("pwd_length:%d",pwd_length);

        memcpy(pwd, keySet->passwd, pwd_length);
        ASCII_TO_INT(pwd, pwd_length);

        keyType = USERS_TYPE_PWD;
        keyNum = SYS_CALL(Users_GetValidId, keyType); // TODO: 参考菜单处理

        //FUNC_BLE_LOG_HEX("pwd:", pwd, pwd_length);//003
        // SUCCESS == SYS_CALL(Users_FindIdleKeyID, keyType, keyNum) 增加密码是否被占用的判断
        UsersAddRes_enum_t AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, RESET);
        FUNC_BLE_LOG_D("AddRes1:%d", AddRes);  
        if (AddRes == ADD_ONCE_OK)
        {  
            AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, SET);
            FUNC_BLE_LOG_D("AddRes2:%d", AddRes);
        }
        switch (AddRes) 
        {
            case ADD_SUCCESS:
                if (keyAttr == USERS_ATTR_PLOY || keyAttr == USERS_ATTR_WEEK)
                {

                }//TODO: 周期密码 
                else
                {
                    FUNC_BLE_LOG_D("Add pwd Success, attr = %d", keyAttr);
                    keySetAck->errno = ERRNO_OK;
                    // if(keyNum == USERS_ID_ADMIN)
                    // {
                    //     Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_MODIFY, keyNum);
                    // }
                    // else
                    //{
                        Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_ADD, keyNum);
                    //}
                }
                break;
            
            case ADD_ERR_TOO_SIMPLE:
                keySetAck->errno = ERRNO_PWD_ILLEGAL;
                break;
            case ADD_ERR_EXISTS:
                keySetAck->errno = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_RANGE:
                keySetAck->errno = ERRNO_PWD_ILLEGAL;
                break;
            case ADD_ERR_CARD_EXISTS:
                keySetAck->errno = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_KEYS_LIB_IS_FULL:
                keySetAck->errno = ERRNO_PWD_FULL;
                break;
            default:
                keySetAck->errno = ERRNO_UNKNOWN;
                break;
        }
        keySetAck->new_id = (uint16_t)(keyNum + 1); // OSAL_SWAP16((uint16_t)keyNum + 1)
        keySetAck->type = UNLOCK_PWD;  //TODO:确认是否要用 
        keySetAck->pwd_type = PWD_TYPE_LONG_TIME;//TODO: 周期密码的周期处理       
        keySetAck->period = 0; //TODO： 周期密码的周期处理
        keySetAck->start_min = 0;
        keySetAck->end_min = 0;
        keySetAck->start_timestamp = 0;
        keySetAck->end_timestamp = 0;
        memcpy(keySetAck->passwd, keySet->passwd, sizeof(keySetAck->passwd));
    }
    else if(keySet->pwd_type == 2) //TODO: 1  周期密码
    {
        //时间策略密码
        for(uint8_t i = 0; i < sizeof(pwd); i++)
        {
            if(keySet->passwd[i] != 0)
            {
                pwd_length++;
            }
            else
            {
                break;
            }
        }
        FUNC_BLE_LOG_D("pwd_length:%d",pwd_length);
        memcpy(pwd, keySet->passwd, pwd_length);
        ASCII_TO_INT(pwd, pwd_length);
        keyType = USERS_TYPE_PWD;
        keyNum = SYS_CALL(Users_GetValidId, keyType); // TODO: 参考菜单处理
        keyAttr = USERS_ATTR_PLOY;//TODO:
        // SUCCESS == SYS_CALL(Users_FindIdleKeyID, keyType, keyNum) 增加密码是否被占用的判断
        UsersAddRes_enum_t AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, RESET);
        FUNC_BLE_LOG_D("AddRes1:%d", AddRes);  
        if (AddRes == ADD_ONCE_OK)
        {  
            AddRes = SYS_CALL(Users_Add, keyType, keyNum, pwd, pwd_length, keyAttr, SET);
            FUNC_BLE_LOG_D("AddRes2:%d", AddRes);
        }
        switch (AddRes) 
        {
            case ADD_SUCCESS:
                if (keyAttr == USERS_ATTR_PLOY || keyAttr == USERS_ATTR_WEEK)
                {
                    AttrPloy.attr       = keyAttr;//
                    AttrPloy.ploy.week  = keySet->period;
                    AttrPloy.ploy.stime = keySet->start_timestamp;
                    AttrPloy.ploy.etime = keySet->end_timestamp;
                    if (SYS_CALL(Users_SetAttrPloy, keyType, keyNum, AttrPloy.attr, &AttrPloy.ploy) == SUCCESS)// USERS_TYPE_PWD
                    {
                        keySetAck->errno = ERRNO_OK;
                        Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_ADD, keyNum);  
                        FUNC_BLE_LOG_D("Set attr Success, keyAttr = %d", keyAttr);
                    }
                    else
                    {
                        keySetAck->errno = ERRNO_UNKNOWN;
                        FUNC_BLE_LOG_D("Set key attr Failed!");
                        if (SYS_CALL(Users_Del, keyType, keyNum, NULL, 0) == USERS_DEL_ERR)
                        {
                            FUNC_BLE_LOG_D("delete key error");
                        }
                        else
                        {   // 删除成功
                            Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_DELETE, keyNum);
                        }
                    }

                }//TODO: 周期密码 
                // else
                // {
                //     FUNC_BLE_LOG_D("Add pwd Success, attr = %d", keyAttr);
                //     keySetAck->errno = ERRNO_OK;
                //     // if(keyNum == USERS_ID_ADMIN)
                //     // {
                //     //     Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_MODIFY, keyNum);
                //     // }
                //     // else
                //     //{
                //         Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keyType, EVENT_CODE_ADD, keyNum);
                //     //}
                // }
                break;
            
            case ADD_ERR_TOO_SIMPLE:
                keySetAck->errno = ERRNO_PWD_ILLEGAL;
                break;
            case ADD_ERR_EXISTS:
                keySetAck->errno = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_RANGE:
                keySetAck->errno = ERRNO_PWD_ILLEGAL;
                break;
            case ADD_ERR_CARD_EXISTS:
                keySetAck->errno = ERRNO_PWD_REPETITION;
                break;
            case ADD_ERR_KEYS_LIB_IS_FULL:
                keySetAck->errno = ERRNO_PWD_FULL;
                break;
            default:
                keySetAck->errno = ERRNO_UNKNOWN;
                break;
        }
        keySetAck->new_id = (uint16_t)(keyNum + 1); 
        keySetAck->type = UNLOCK_PWD; 
        keySetAck->pwd_type = PWD_TYPE_PERIOD;//TODO: 周期密码的周期处理       
        keySetAck->period = AttrPloy.ploy.week ; //TODO： 周期密码的周期处理
        keySetAck->start_min = keySet->start_min;
        keySetAck->end_min = keySet->start_min;
        keySetAck->start_timestamp = AttrPloy.ploy.stime;
        keySetAck->end_timestamp = AttrPloy.ploy.etime;
        memcpy(keySetAck->passwd, keySet->passwd, sizeof(keySetAck->passwd));
    }
    // else if (keySet->pwd_type == 1)
    // {

    // }

    memcpy(KeySetAck_Send.Payload.dataBuf, &keySetAck->new_id, sizeof(Ble_keySet_ack_stu_t)); 
    FUNC_BLE_LOG_D("sizeof(Ble_keySet_ack_stu_t):%d",sizeof(Ble_keySet_ack_stu_t));//确认好后, 去掉 
    BleRevMain_send_Cmd(&KeySetAck_Send, KeySetAck_Send.dataLen);
    OSAL_Free(pAckBuff);
}

/**
 * @brief 远程查看锁所有密码
 *
 *
 * @note
 */
static void FuncBle_Get_Pwd_Info(uint8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t GetPwdInfo_Send = {0};
    Ble_genaral_rev_t *GetPwdInfo = Data;
    Ble_GetPwdInfo_ack_stu_t *GetPwdInfoAck = NULL;
    Ble_Password_stu_t pwdPloy; 
    Ble_Fpt_stu_t fpt;
    Ble_Card_stu_t card;
    uint16_t vts_temp = 0;
    uint8_t pwdQty = 0;
    uint8_t fptQty = 0;
    uint8_t cardQty = 0;
    uint8_t keyType = 0, ackBuffLen = 0;
    uint8_t *pAckBuff = NULL;

    memset(&pwdPloy, 0xff, sizeof(Ble_Password_stu_t));
    pwdQty  = SYS_CALL(Users_GetQty, USERS_TYPE_PWD, 1); //读取密码数量
    fptQty  = SYS_CALL(Users_GetQty, USERS_TYPE_FPT, 1); //读取指纹数量
    cardQty = SYS_CALL(Users_GetQty, USERS_TYPE_CARD, 1); //读取卡片数量
    if((pwdQty+fptQty+cardQty) == 0)
    {
        ackBuffLen = sizeof(pwd_info_t)  + 2;
    }
    else
    {
        ackBuffLen = sizeof(pwd_info_t) * (pwdQty+fptQty+cardQty) + 2;
    }
    
    pAckBuff = OSAL_Malloc(ackBuffLen);
    if (pAckBuff == NULL)
    {
        FUNC_BLE_LOG_W("malloc error");
        return;
    }

    memset(pAckBuff,0,ackBuffLen);
    GetPwdInfoAck = (Ble_GetPwdInfo_ack_stu_t *)pAckBuff;

    FUNC_BLE_LOG_D("pwdQty:%d",pwdQty);
    FUNC_BLE_LOG_D("fptQty:%d",fptQty);
    FUNC_BLE_LOG_D("cardQty:%d",cardQty);
    FUNC_BLE_LOG_D("ackBuffLen:%d",ackBuffLen);
    FUNC_BLE_LOG_HEX("FuncBle_Get_Pwd_Info:", Data, len);

    GetPwdInfo_Send.dataLen =  ackBuffLen + 12;
    GetPwdInfo_Send.dst_addr = APP;
    GetPwdInfo_Send.src_addr = LKMD;
    GetPwdInfo_Send.random_code = random_code_global;
    vts_temp = (GetPwdInfo->vts & 0xFF00) | ((uint16_t)((uint8_t)GetPwdInfo->vts & 0xF3));
    GetPwdInfo_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    GetPwdInfo_Send.Payload.cmd = OSAL_SWAP16(BLE_GET_PWD_INFO);
    GetPwdInfoAck->id_num = pwdQty+fptQty+cardQty; 

    //密码
    keyType = USERS_TYPE_PWD;
    for(uint16_t i = 0; i < pwdQty; i++)
    {
        //上报的id 加1 
        if(SYS_CALL(Users_ReadKeys, keyType, i, &pwdPloy) == SUCCESS)
        {
            if(pwdPloy.attr == USERS_ATTR_PLOY || pwdPloy.attr == USERS_ATTR_WEEK)
            {
                GetPwdInfoAck->infos[i].unlock_type = UNLOCK_PERIOD_PWD; 
                GetPwdInfoAck->infos[i].pwd_id      = i + 1;
            }
            else if(pwdPloy.attr == USERS_ATTR_FOREVER)
            {
                GetPwdInfoAck->infos[i].unlock_type = UNLOCK_PWD; 
                GetPwdInfoAck->infos[i].pwd_id      = i + 1;   
            }
            // else  // TODO:临时密码是否也要放在NV里面
            // {
            //     GetPwdInfoAck->infos[i].unlock_type = PWD_TYPE_TEMPORARY; 
            //     GetPwdInfoAck->infos[i].pwd_id      = OSAL_SWAP16(i + 1);
            // }
        }

    }
    //指纹
    keyType = USERS_TYPE_FPT;
    for(uint16_t i = 0; i < fptQty; i++)
    {
        //上报的id 加51 
        if(SYS_CALL(Users_ReadKeys, keyType, i, &fpt) == SUCCESS)
        {          
            GetPwdInfoAck->infos[i+pwdQty].unlock_type = UNLOCK_FINGER; 
            GetPwdInfoAck->infos[i+pwdQty].pwd_id      = i + 51;   
        }
    }
    //卡片
    keyType = USERS_TYPE_CARD;
    for(uint16_t i = 0; i < cardQty; i++)
    {
        //上报的id 加101 
        if(SYS_CALL(Users_ReadKeys, keyType, i, &card) == SUCCESS)
        {          
            GetPwdInfoAck->infos[i+pwdQty+fptQty].unlock_type = UNLOCK_CARD; 
            GetPwdInfoAck->infos[i+pwdQty+fptQty].pwd_id      = i + 101;   
        }
    }
    
    memcpy(GetPwdInfo_Send.Payload.dataBuf, &GetPwdInfoAck->id_num, ackBuffLen);
    BleRevMain_send_Cmd((uint8_t *)&GetPwdInfo_Send.dataLen, GetPwdInfo_Send.dataLen);
    OSAL_Free(pAckBuff);
}

/**
 * @brief 添加指纹(0x9020)
 *
 *
 * @note
 */
static void FuncBle_Add_Finger(uint8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t AddFingerAck_Send = {0};
    Ble_genaral_rev_t *AddFinger = Data;
    int16_t ret_code = 0;
    uint16_t vts_temp = 0;
    uint8_t keynumber = 0;
    //uint16_t audioNum = 0;
    FUNC_BLE_LOG_HEX("FuncBle_Add_Finger:", Data, len);

    AddFingerAck_Send.dataLen =  0x000E;
    AddFingerAck_Send.dst_addr = APP;
    AddFingerAck_Send.src_addr = LKMD;
    AddFingerAck_Send.random_code = random_code_global; 
    vts_temp = (AddFinger->vts & 0xFF00) | ((uint16_t)((uint8_t)AddFinger->vts & 0xF3));//
    AddFingerAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    AddFingerAck_Send.Payload.cmd = OSAL_SWAP16(BLE_ADD_FINGER);

    keynumber = SYS_CALL(Users_GetValidId, USERS_TYPE_FPT);
    if (keynumber == 0xFF)
    {
        /* 没有空闲的存储，该类型密钥已满 */
        // 切换菜单时会判断密钥是否满
        // audioNum = ZHI_WEN_KU_YI_MAN;
        // Audio_Play(audioNum, RESET); //TODO:是否要提示指纹库已满
        ret_code = SET_FAILED;
    }
    else
    {
         ret_code = SET_SUCCESS;
         Menu_StartAppAddKeys(USERS_TYPE_FPT, keynumber);
         /* 更新休眠时间 */
         //   OSAL_UpdateSleepTime(OSAL_GetAutoSleepTime() + AUTO_SLEEP_TIME, 1);
    }

    memcpy(AddFingerAck_Send.Payload.dataBuf, &ret_code, sizeof(ret_code));
    BleRevMain_send_Cmd((uint8_t *)&AddFingerAck_Send.dataLen, AddFingerAck_Send.dataLen);
    //创建注册超时定时器
    if (fptadd_timeout_Timer == NULL)
    {
        fptadd_timeout_Timer = OSAL_TimerCreate(Add_Finger_Timeout_Callback, FPTADD_TIMEOUT_TIME, RESET);
        FUNC_BLE_LOG_D("add fpt Create fptadd_timeout_Timer");
    }
}

/**
 * @brief  取消添加指纹(0x9022)
 *
 *
 * @note
 */
static void FuncBle_Cancel_Add_Finger(uint8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t CancelAddFingerAck_Send = {0};
    Ble_genaral_rev_t *CancelAddFinger = Data;
    int16_t ret_code = 0;
    uint16_t vts_temp = 0;
    FUNC_BLE_LOG_HEX("FuncBle_Cancel_Add_Finger:", Data, len);

    CancelAddFingerAck_Send.dataLen =  0x000E;
    CancelAddFingerAck_Send.dst_addr = APP;
    CancelAddFingerAck_Send.src_addr = LKMD;
    CancelAddFingerAck_Send.random_code = random_code_global; 
    vts_temp = (CancelAddFinger->vts & 0xFF00) | ((uint16_t)((uint8_t)CancelAddFinger->vts & 0xF3));
    CancelAddFingerAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    CancelAddFingerAck_Send.Payload.cmd = OSAL_SWAP16(BLE_CANCEL_ADD_FINGER);

    ret_code = SET_SUCCESS;
    //取消添加指纹，有添加指纹失败的声音提示
    //TODO: 是否有取消失败的情况
    Menu_Exit_Managemode();
    memcpy(CancelAddFingerAck_Send.Payload.dataBuf, &ret_code, sizeof(ret_code));
    BleRevMain_send_Cmd((uint8_t *)&CancelAddFingerAck_Send.dataLen, CancelAddFingerAck_Send.dataLen);
}

/**
 * @brief 删除指纹
 *
 *
 * @note
 */
static void FuncBle_Del_Finger(uint8_t len, Ble_FingerDel_stu_t *Data)
{
    BleAckPacket_stu_t FingerDelAck_Send = {0};
    Ble_FingerDel_stu_t *FingerDel = (Ble_FingerDel_stu_t *)Data;
    UsersNumStatus_enum_t res; 
    uint16_t vts_temp = 0;
    uint8_t keysNumber = 0XFF;
    int16_t ret_code = 0;

    FUNC_BLE_LOG_HEX("FuncBle_Del_Finger:", Data, len);
    FingerDelAck_Send.dataLen =  0x000E;
    FingerDelAck_Send.dst_addr = APP;
    FingerDelAck_Send.src_addr = LKMD;
    FingerDelAck_Send.random_code = random_code_global; 
    vts_temp = (FingerDel->vts & 0xFF00) | ((uint16_t)((uint8_t)FingerDel->vts & 0xF3));
    FingerDelAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    FingerDelAck_Send.Payload.cmd = OSAL_SWAP16(BLE_DEL_FINGER);
 
    keysNumber = FingerDel->pwd_id - 51;
    FUNC_BLE_LOG_D("keysNumber:%d", keysNumber);
    res = SYS_CALL(Users_KeyNumIsExist, USERS_TYPE_FPT, keysNumber);
    if (res == USERS_NUMBER_EXISTED) 
    {
        if(SYS_CALL(Users_Del, USERS_TYPE_FPT, keysNumber, NULL, 0) == USERS_DEL_ERR)
        { 
            ret_code = SET_FAILED;
        }
        else
        {
            ret_code = SET_SUCCESS;
            Local_LockSaveRecord(EVENT_TYPE_PROGRAM, USERS_TYPE_FPT, EVENT_CODE_DELETE, keysNumber);
        }
    }
    else
    {
        ret_code = SET_FAILED;
    }
    
    memcpy(FingerDelAck_Send.Payload.dataBuf, &ret_code, sizeof(ret_code)); 
    BleRevMain_send_Cmd((uint8_t *)&FingerDelAck_Send.dataLen, FingerDelAck_Send.dataLen);
}

/**
 * @brief  获取App删除卡片标识
 * @note
 *
 * @return App删除卡片标识
 */
FlagStatus Menu_GetAppAddCardFlag(void)
{
	return appDelCardFlag;
}

/**
 * @brief  设置App删除卡片标识
 * @note
 *
 * 
 */
void Menu_SetAppAddCardFlag(FlagStatus delflag)
{
    appDelCardFlag = delflag;
}

/**
 * @brief 远程删除本地密码
 *
 *
 * @note
 */
static void FuncBle_Del_Local_Pwd(uint8_t len, Ble_keyDel_stu_t *Data)
{
    BleAckPacket_stu_t KeyDelAck_Send = {0};
    Ble_keyDel_stu_t *keyDel = (Ble_keyDel_stu_t *)Data;
    Ble_keyDel_ack_stu_t *keyDelAck = NULL;
    UsersNumStatus_enum_t res; 
    uint16_t vts_temp = 0;
    uint8_t keysNumber = 0XFF;
    uint8_t keysType = 0;
    uint8_t ackBuffLen = 0;
    uint8_t *pAckBuff = NULL;
    Ble_Card_stu_t card_data;

    ackBuffLen = sizeof(Ble_keyDel_ack_stu_t); 
    pAckBuff = OSAL_Malloc(ackBuffLen);
    if (pAckBuff == NULL)
    {
        FUNC_BLE_LOG_W("malloc error");
        return;
    }
    memset(pAckBuff,0,ackBuffLen);
    keyDelAck = (Ble_keyDel_ack_stu_t *)pAckBuff;
    FUNC_BLE_LOG_HEX("FuncBle_Del_Local_Pwd:", Data, len);

    KeyDelAck_Send.dataLen =  ackBuffLen + 12;
    KeyDelAck_Send.dst_addr = APP;
    KeyDelAck_Send.src_addr = LKMD;
    KeyDelAck_Send.random_code = random_code_global; 
    vts_temp = (keyDel->vts & 0xFF00) | ((uint16_t)((uint8_t)keyDel->vts & 0xF3));
    KeyDelAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    KeyDelAck_Send.Payload.cmd = OSAL_SWAP16(BLE_DEL_LOCAL_PWD);

    //根据id来区分密码, 指纹, 卡片的类型 
    if (keyDel->id >= 1 && keyDel->id <= 50)
    {
        keysNumber = keyDel->id - 1;
        keysType = USERS_TYPE_PWD;
    }
    else if(keyDel->id >= 51 && keyDel->id <= 100)
    {
        keysNumber = keyDel->id - 51;
        keysType = USERS_TYPE_FPT;
    }
    else if(keyDel->id >= 101 && keyDel->id <= 150)
    {
        keysNumber = keyDel->id - 101;
        keysType = USERS_TYPE_CARD;
    }
    else
    {
        //id 不对,不删除密钥
        FUNC_BLE_LOG_D("keyDel->id:%d", keyDel->id);
    }
    FUNC_BLE_LOG_D("keysNumber:%d keysType:%d", keysNumber, keysType);
    
    //id在范围内才删除密钥
    if(keyDel->id >= 1 && keyDel->id <= 150)//keysNumber : 0,49
    {
        res = SYS_CALL(Users_KeyNumIsExist, keysType, keysNumber);
        if (res == USERS_NUMBER_EXISTED) 
        {
            if(SYS_CALL(Users_Del, keysType, keysNumber, NULL, 0) == USERS_DEL_ERR)
            { 
                keyDelAck->ret_code = SET_FAILED;
            }
            else
            {
                if (keysType == USERS_TYPE_FPT)
				{
                    Finger_DeleteImage(keysNumber, 1);
				}
                else if (keysType == USERS_TYPE_CARD)
                {
                    //发送指令给MC60， 删除特定ID的白卡  TODO：删除失败处理
                    if(SYS_CALL(Users_ReadKeys, USERS_TYPE_CARD, keysNumber, &card_data) == SUCCESS)
                    {
                        FUNC_BLE_LOG_HEX("card_data.card: ", card_data.card, sizeof(card_data.card));
                    }
                   // 要删除对应的card id TODO:删除失败处理
                   SYS_CALL(MC60_Send_Del_Id_Nfc, card_data.card[0]);
                   //app 删除卡片
                    Menu_SetAppAddCardFlag(SET);
                }
                keyDelAck->ret_code = SET_SUCCESS;
                Local_LockSaveRecord(EVENT_TYPE_PROGRAM, keysType, EVENT_CODE_DELETE, keysNumber);
            }
        }
        else
        {
            keyDelAck->ret_code = SET_FAILED;
        }
    }
    else
    {
        keyDelAck->ret_code = SET_FAILED;
    }
    keyDelAck->id = keyDel->id;
    memcpy(KeyDelAck_Send.Payload.dataBuf, &keyDelAck->id, sizeof(Ble_keyDel_ack_stu_t)); 
    BleRevMain_send_Cmd((uint8_t *)&KeyDelAck_Send.dataLen, KeyDelAck_Send.dataLen);
    OSAL_Free(pAckBuff);
}

/**
 * @brief 卡片录入(0x9050)
 *
 *
 * @note
 */
static void FuncBle_Add_Nfc(uint8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t AddNfcAck_Send = {0};
    Ble_Nfcadd_ack_stu_t *AddNfcAck = NULL;
    Ble_genaral_rev_t *AddNfc = Data;
    uint16_t vts_temp = 0;
    uint8_t keynumber = 0;
    uint8_t ackBuffLen = 0;
    uint8_t *pAckBuff = NULL;

    ackBuffLen = sizeof(Ble_Nfcadd_ack_stu_t); 
    pAckBuff = OSAL_Malloc(ackBuffLen);
    if (pAckBuff == NULL)
    {
        FUNC_BLE_LOG_W("malloc error");
        return;
    }

    memset(pAckBuff,0,ackBuffLen);
    AddNfcAck = (Ble_Nfcadd_ack_stu_t *)pAckBuff;

    FUNC_BLE_LOG_HEX("FuncBle_Add_Nfc:", Data, len);
    AddNfcAck_Send.dataLen =  ackBuffLen + 12;
    AddNfcAck_Send.dst_addr = APP;
    AddNfcAck_Send.src_addr = LKMD;
    AddNfcAck_Send.random_code = random_code_global; 
    vts_temp = (AddNfc->vts & 0xFF00) | ((uint16_t)((uint8_t)AddNfc->vts & 0xF3));
    AddNfcAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    AddNfcAck_Send.Payload.cmd = OSAL_SWAP16(BLE_ADD_NFC);

    keynumber = SYS_CALL(Users_GetValidId, USERS_TYPE_CARD);
    FUNC_BLE_LOG_D("keynumber:%d", keynumber);
    if (keynumber == 0xFF)
    {
        /* 没有空闲的存储，该类型密钥已满 */
        // 切换菜单时会判断密钥是否满
        // audioNum = ZHI_WEN_KU_YI_MAN;
        // Audio_Play(audioNum, RESET); //TODO:是否要提示卡片库已满
        AddNfcAck->result = SET_FAILED;
    }
    else
    {
         AddNfcAck->result = SET_SUCCESS; //0-成功 1-失败
         Menu_StartAppAddKeys(USERS_TYPE_CARD, keynumber); //001 待确认
         /* 更新休眠时间 */
         //   OSAL_UpdateSleepTime(OSAL_GetAutoSleepTime() + AUTO_SLEEP_TIME, 1);
    }

    memcpy(AddNfcAck_Send.Payload.dataBuf, &AddNfcAck->result, sizeof(Ble_Nfcadd_ack_stu_t)); 
    BleRevMain_send_Cmd((uint8_t *)&AddNfcAck_Send.dataLen, AddNfcAck_Send.dataLen);
    OSAL_Free(pAckBuff);

    //创建注册超时定时器
    if (nfcadd_timeout_Timer == NULL) //TODO: 创建超时定时器?  还是 在超时退出管理菜单时，上报录入超时 
    {
        nfcadd_timeout_Timer = OSAL_TimerCreate(Add_Nfc_Timeout_Callback, NFCADD_TIMEOUT_TIME, RESET);
        FUNC_BLE_LOG_D("add nfc Create nfcadd_timeout_Timer");
    }
}

/**
 * @brief  取消卡片录入(0x9051)
 *
 *
 * @note
 */
static void FuncBle_Cancel_Add_Nfc(uint8_t len, Ble_genaral_rev_t *Data)
{
    BleAckPacket_stu_t CancelAddNfcAck_Send = {0};
    Ble_genaral_rev_t *CancelAddNfc = Data;
    int16_t result = 0;
    uint16_t vts_temp = 0;
    FUNC_BLE_LOG_HEX("FuncBle_Cancel_Add_Nfc:", Data, len);

    CancelAddNfcAck_Send.dataLen =  0x000E;
    CancelAddNfcAck_Send.dst_addr = APP;
    CancelAddNfcAck_Send.src_addr = LKMD;
    CancelAddNfcAck_Send.random_code = random_code_global; 
    vts_temp = (CancelAddNfc->vts & 0xFF00) | ((uint16_t)((uint8_t)CancelAddNfc->vts & 0xF3));
    CancelAddNfcAck_Send.Payload.vts = OSAL_SWAP16(vts_temp);
    CancelAddNfcAck_Send.Payload.cmd = OSAL_SWAP16(BLE_CANCEL_ADD_NFC);

    result = SET_SUCCESS;
    //取消添加卡片，有添加卡片失败的声音提示 ? 001 
    //TODO: 是否有取消失败的情况
    uint8_t Menu_Exit_Managemode(void);
    Menu_Exit_Managemode();
    memcpy(CancelAddNfcAck_Send.Payload.dataBuf, &result, sizeof(result));
    BleRevMain_send_Cmd((uint8_t *)&CancelAddNfcAck_Send.dataLen, CancelAddNfcAck_Send.dataLen);
}

/**
 * @brief 获取锁的音量(0x8068)
 *
 *
 * @note 
 */
static void FuncBle_Get_Volume(uint8_t len, Ble_genaral_rev_t *Data)
{
    get_volume_stu_t GetVolume_Ack = {0};
    Ble_genaral_rev_t *GetVolume = Data;
    uint16_t vts_temp = 0;
    uint8_t audioMode = RESET;
    uint8_t voice = 0;

    FUNC_BLE_LOG_HEX("FuncBle_Get_Volume:", Data, len);
    vts_temp = (GetVolume->vts & 0xFF00) | ((uint16_t)((uint8_t)GetVolume->vts & 0xF3));
    audioMode = Audio_GetMuteMode();
    if (audioMode == SET) //静音状态下
    {
        voice = 1; //1 – 静音
    }
    else
    {
        voice = Audio_GetVolume();
        switch (voice)
        {
            case 60:
                voice = 2;//2 – 低，
                break;
            case 80:
                voice = 3;// 3 – 中
            break;
                case 100:
                voice = 4;//4 – 高
            break;
            default:
                voice = 4;
                break;
        }
    }
    GetVolume_Ack.voice_volume = voice;//
    GetVolume_Ack.doorbell_volume = 1;//没有门铃--门铃音量 1 – 静音
    FUNC_BLE_LOG_D("voice_volume:%d", GetVolume_Ack.voice_volume);
    FuncBle_general_send_Handle( OSAL_SWAP16(vts_temp), OSAL_SWAP16(BLE_GET_VOLUME), sizeof(get_volume_stu_t), (uint8_t *)&GetVolume_Ack.voice_volume);
}

/**
 * @brief 获取锁端电量(0x8064)
 *
 *
 * @note 
 */
static void FuncBle_Get_Power_Value(uint8_t len, Ble_genaral_rev_t *Data)
{
    get_powervalue_stu_t Get_PowerValue_Ack = {0};
    Ble_genaral_rev_t *Get_PowerValue = Data;
    uint16_t vts_temp = 0;
    uint8_t bat = SYS_CALL(Battery_Get);

    FUNC_BLE_LOG_HEX("FuncBle_Get_Power_Value:", Data, len);
    vts_temp = (Get_PowerValue->vts & 0xFF00) | ((uint16_t)((uint8_t)Get_PowerValue->vts & 0xF3));
   
    Get_PowerValue_Ack.battery_value = bat;
    Get_PowerValue_Ack.power_value = -1;//[0 - 100] 充电电池电量值(没有填-1)
    FUNC_BLE_LOG_D("battery_value:%d", Get_PowerValue_Ack.battery_value);
    FuncBle_general_send_Handle(OSAL_SWAP16(vts_temp), OSAL_SWAP16(BLE_GET_POWR_VALUE), sizeof(get_powervalue_stu_t), (uint8_t *)&Get_PowerValue_Ack.battery_value);
}

/**
 * @brief 设置自动闭锁时间(0x8095)
 *
 *
 * @note 
 */
static void FuncBle_Set_AutoLock_Time(uint8_t len, Ble_Setting_AutoLock_Time_stu_t *Data)
{
    Ble_Setting_AutoLock_Time_Ack_stu_t Set_AutoLock_Time_Ack = {0};
    Ble_Setting_AutoLock_Time_stu_t *Set_AutoLock_Time = Data;
    uint16_t vts_temp = 0;
    int8_t result = 1; //0 – 成功， 1 – 失败
    uint16_t auto_locktime;
    uint8_t mode = 0;

    FUNC_BLE_LOG_HEX("FuncBle_Set_AutoLock_Time:", Data, len);
    vts_temp = (Set_AutoLock_Time->vts & 0xFF00) | ((uint16_t)((uint8_t)Set_AutoLock_Time->vts & 0xF3));
    
    auto_locktime = Set_AutoLock_Time->auto_lock_time;

    if(auto_locktime == 0)//TODO：范围判断
    {
        mode = MANUAL_MODE;
        if (OSAL_NvWrite(SYS_OFFSET(amMode), &mode, sizeof(mode)) == SUCCESS)
        { 
            // 设置同步上锁模式
            Lock_ModeSync(mode);
            result = 0; 
        }
    }
    else
    {
        if (OSAL_NvWrite(SYS_OFFSET(auto_lock_time), &auto_locktime, sizeof(auto_locktime)) == SUCCESS)
        {
            SYS_CALL(Local_LockUpdateAutoLockTime, auto_locktime);
            //Menu_OpenAutoLock();  
            mode = AUTO_MODE;
            if (OSAL_NvWrite(SYS_OFFSET(amMode), &mode, sizeof(mode)) == SUCCESS)
            {
                // 设置同步上锁模式
                Lock_ModeSync(mode);
                result = 0;  
            }
        }
    }  

    Set_AutoLock_Time_Ack.result = result;
    Set_AutoLock_Time_Ack.auto_lock_time = auto_locktime;
    FUNC_BLE_LOG_D("result:%d auto_locktime:%d", result, auto_locktime);
    FuncBle_general_send_Handle(OSAL_SWAP16(vts_temp), OSAL_SWAP16(BLE_SETTING_AUTO_LOCK_TIME), sizeof(Ble_Setting_AutoLock_Time_Ack_stu_t), (uint8_t *)&Set_AutoLock_Time_Ack.result);
}
/**
 * @brief 获取自动闭锁时间 (0x8096)
 *
 *
 * @note 
 */ 
static void FuncBle_Get_AutoLock_Time(uint8_t len, Ble_genaral_rev_t *Data)
{
    Ble_Get_AutoLock_Time_stu_t AutoLock_Time_Ack = {0};
    Ble_genaral_rev_t *AutoLock_Time = Data;
    uint16_t vts_temp = 0;
    uint8_t lockMode = 0;
    uint8_t nv_autoLockTime = DEFAULT_AUTO_LOCK_TIME;

    FUNC_BLE_LOG_HEX("FuncBle_Get_AutoLock_Time:", Data, len);
    vts_temp = (AutoLock_Time->vts & 0xFF00) | ((uint16_t)((uint8_t)AutoLock_Time->vts & 0xF3));

   if (OSAL_NvRead(SYS_OFFSET(amMode), &lockMode, sizeof(lockMode)) == SUCCESS)
   {
       if(MANUAL_MODE == lockMode)
       {
           nv_autoLockTime = 0;
       }
       else
       {
           if (OSAL_NvRead(SYS_OFFSET(auto_lock_time), &nv_autoLockTime, sizeof(nv_autoLockTime)) == ERROR)
           {
               nv_autoLockTime = 0;
           }
       }
   }
   else
   {
       nv_autoLockTime = 0;
   }

   
    AutoLock_Time_Ack.auto_lock_time = nv_autoLockTime;
    FUNC_BLE_LOG_D("autolock_time:%d", AutoLock_Time_Ack.auto_lock_time);
    FuncBle_general_send_Handle(OSAL_SWAP16(vts_temp), OSAL_SWAP16(BLE_GET_AUTO_LOCK_TIME), sizeof(Ble_Get_AutoLock_Time_stu_t), (uint8_t *)&AutoLock_Time_Ack.auto_lock_time);
}
/************************************ 锁主动发给APP的指令 ************************************/
/**
 * @brief 锁去请求APP下发网络时间
 *
 *
 * @note
 */
static void FunBle_Lock_GetUtcTime(void)
{
    BleAckPacket_stu_t LockGettime_send = {0};
    uint8_t ackBuffLen = 0;
    uint16_t vts_temp = 0;
    uint16_t ver = BLE_MESSAGE_VER;
    uint16_t type = BLE_CON;

    Lock_seq++;
    if (Lock_seq >= 0x03FF)
    {
        Lock_seq = 0;
    }
    ackBuffLen = sizeof(Ble_genaral_rev_t);
    LockGettime_send.dataLen = ackBuffLen + 8;
    LockGettime_send.dst_addr = APP;
    LockGettime_send.src_addr = LKMD;
    LockGettime_send.random_code = random_code_global; 

    vts_temp =  (ver << 12) | (type << 10) | Lock_seq;
    FUNC_BLE_LOG_D("ver:%d",ver);
    FUNC_BLE_LOG_D("type:%d",type);
    FUNC_BLE_LOG_D("Lock_seq:%d",Lock_seq);
    FUNC_BLE_LOG_D("vts_temp:%04x",vts_temp);

    LockGettime_send.Payload.vts = vts_temp;
    LockGettime_send.Payload.cmd = OSAL_SWAP16(BLE_GET_UTC_TIME);
    BleRevMain_send_Cmd((uint8_t *)&LockGettime_send.dataLen, LockGettime_send.dataLen);
}

/**
 * @brief 发送同步网络时间指令
 *
 * @param [in] xTimer
 *
 * @note
 */
static void Send_Getutctime_cmd_Callback(TimerHandle_stu_t xTimer)
{
    getutctime_Timer = NULL;
    FunBle_Lock_GetUtcTime();
}

/**
 * @brief 指纹注册进度通知
 *
 *
 * @note
 */
static void FunBle_Enroll_Finger_Notify(Ble_enroll_finer_ack_stu_t *Data)
{
    BleAckPacket_stu_t Ble_enrollfiner_ack_send = {0};
    Ble_enroll_finer_ack_stu_t Ble_enrollfiner_ack = {0};
    uint16_t vts_temp = 0;
    uint16_t ver = BLE_MESSAGE_VER;
    uint16_t type = BLE_NON;

    Lock_seq++;
    if (Lock_seq >= 0x03FF)
    {
        Lock_seq = 0;
    }
    Ble_enrollfiner_ack_send.dataLen = sizeof(Ble_enroll_finer_ack_stu_t) + 12; 
    Ble_enrollfiner_ack_send.dst_addr = APP;
    Ble_enrollfiner_ack_send.src_addr = LKMD;
    Ble_enrollfiner_ack_send.random_code = random_code_global; 
    vts_temp =  (ver << 12) | (type << 10) | Lock_seq;
    Ble_enrollfiner_ack_send.Payload.vts = vts_temp;
    Ble_enrollfiner_ack_send.Payload.cmd = OSAL_SWAP16(BLE_ENROLL_FINGER_NOTIFY);
    Ble_enrollfiner_ack.percentage = Data->percentage;
    Ble_enrollfiner_ack.state = Data->state;
    Ble_enrollfiner_ack.pwd_id = Data->pwd_id;
    FUNC_BLE_LOG_D("ack.percentage :%d",Ble_enrollfiner_ack.percentage);
    FUNC_BLE_LOG_D("ack.state :%d",Ble_enrollfiner_ack.state);
    FUNC_BLE_LOG_D("ack.pwd_id :%d",Ble_enrollfiner_ack.pwd_id);
    memcpy(Ble_enrollfiner_ack_send.Payload.dataBuf, &Ble_enrollfiner_ack.percentage, sizeof(Ble_enroll_finer_ack_stu_t)); 
    BleRevMain_send_Cmd((uint8_t *)&Ble_enrollfiner_ack_send.dataLen, Ble_enrollfiner_ack_send.dataLen);
}

/**
 * @brief 指纹注册的超时上报
 *
 * @param [in] xTimer
 *
 * @note
 */
static void Add_Finger_Timeout_Callback(TimerHandle_stu_t xTimer)
{
    fptadd_timeout_Timer = NULL;
    Ble_enroll_finer_ack_stu_t Ble_enrollfiner_ack = {0};
    //取消添加指纹，有添加指纹失败的声音提示
    //退出指纹添加
    Menu_Exit_Managemode();

    Ble_enrollfiner_ack.percentage = Ble_enrollfiner_ack_temp.percentage;
    Ble_enrollfiner_ack.state = ENROLL_TIMEOUT;
    Ble_enrollfiner_ack.pwd_id = Ble_enrollfiner_ack_temp.pwd_id;//
    FunBle_Enroll_Finger_Notify(&Ble_enrollfiner_ack);

    memset(&Ble_enrollfiner_ack_temp, 0, sizeof(Ble_enroll_finer_ack_stu_t));
    FUNC_BLE_LOG_D("Add_Finger_Timeout_Callback");
}

/**
 * @brief  Finger_MsgCb
 * @note
 *
 * @param  msg：消息数据
 * @param  len：数据长度
 */
static void Finger_MsgCb(void *msg, uint16_t len)
{
    Ble_enroll_finer_ack_stu_t Ble_enrollfiner_ack = {0};

    FingerMsg_t *finger_msg = (FingerMsg_t *)msg;
    switch (finger_msg->action)
    {
        case FINGER_ACTION_ENTER_AGAIN:
            Ble_enrollfiner_ack.percentage = finger_msg->finger_add_cnt * 20;
            Ble_enrollfiner_ack.state = ENROLL_IN_PROGRESS;
            Ble_enrollfiner_ack.pwd_id = finger_msg->fingerNumber + 51;

            Ble_enrollfiner_ack_temp.percentage = Ble_enrollfiner_ack.percentage;
            Ble_enrollfiner_ack_temp.state = Ble_enrollfiner_ack.state;
            Ble_enrollfiner_ack_temp.pwd_id = Ble_enrollfiner_ack.pwd_id;

            break;
        case FINGER_ACTION_ADD_OK:
            Ble_enrollfiner_ack.percentage = 100;
            Ble_enrollfiner_ack.state = ENROLL_SUCCESS;
            Ble_enrollfiner_ack.pwd_id = finger_msg->fingerNumber + 51;
            break;
        case FINGER_ACTION_ADD_ERR:

            Ble_enrollfiner_ack.percentage = finger_msg->finger_add_cnt * 20;
            Ble_enrollfiner_ack.state = ENROLL_FAILED;
            Ble_enrollfiner_ack.pwd_id = finger_msg->fingerNumber + 51;
            break;
        default:
            return;
    }
    FunBle_Enroll_Finger_Notify(&Ble_enrollfiner_ack);

    if(Ble_enrollfiner_ack.state == ENROLL_IN_PROGRESS)
    {
        if( fptadd_timeout_Timer != NULL )
        {
            OSAL_TimerDelete(fptadd_timeout_Timer);
            FUNC_BLE_LOG_D("Del fptadd_timeout_Timer 1");
            fptadd_timeout_Timer = NULL;
        }
        //创建注册超时定时器
        if (fptadd_timeout_Timer == NULL)
        {
            fptadd_timeout_Timer = OSAL_TimerCreate(Add_Finger_Timeout_Callback, FPTADD_TIMEOUT_TIME, RESET);
            FUNC_BLE_LOG_D("fptcb Create fptadd_timeout_Timer");
        }
    }
    else
    {
        if( fptadd_timeout_Timer != NULL )
        {
            OSAL_TimerDelete(fptadd_timeout_Timer);
            fptadd_timeout_Timer = NULL;
            FUNC_BLE_LOG_D("Del fptadd_timeout_Timer 2");
        }
        // if (ENROLL_SUCCESS == Ble_enrollfiner_ack.state)
        // {
        //     Local_LockSaveRecord(EVENT_TYPE_PROGRAM, USERS_TYPE_FPT, EVENT_CODE_ADD, finger_msg->fingerNumber);
        // }
    }
}

/**
 * @brief 卡片添加结果上报
 *
 *
 * @note
 */
static void FunBle_Enroll_Nfc_Notify(Ble_enroll_nfc_ack_stu_t *Data)
{
    BleAckPacket_stu_t Ble_enrollnfc_ack_send = {0};
    Ble_enroll_nfc_ack_stu_t Ble_enrollnfc_ack = {0};
    uint16_t vts_temp = 0;
    uint16_t ver = BLE_MESSAGE_VER;
    uint16_t type = BLE_NON;
    uint8_t ackBuffLen = 0;

    Lock_seq++;
    if (Lock_seq >= 0x03FF)
    {
        Lock_seq = 0;
    }
    ackBuffLen = sizeof(Ble_enroll_nfc_ack_stu_t); 
    Ble_enrollnfc_ack_send.dataLen = ackBuffLen + 12; 
    Ble_enrollnfc_ack_send.dst_addr = APP;
    Ble_enrollnfc_ack_send.src_addr = LKMD;
    Ble_enrollnfc_ack_send.random_code = random_code_global; 
    vts_temp =  (ver << 12) | (type << 10) | Lock_seq;
    Ble_enrollnfc_ack_send.Payload.vts = vts_temp;
    Ble_enrollnfc_ack_send.Payload.cmd = OSAL_SWAP16(BLE_ENROLL_NFC_NOTIFY);

    Ble_enrollnfc_ack.result = Data->result;
    Ble_enrollnfc_ack.user_id = Data->user_id; 
    FUNC_BLE_LOG_D("result :%d",Ble_enrollnfc_ack.result);
    FUNC_BLE_LOG_D("user_id :%d",Ble_enrollnfc_ack.user_id);
    memcpy(Ble_enrollnfc_ack_send.Payload.dataBuf, &Ble_enrollnfc_ack.result, sizeof(Ble_enroll_nfc_ack_stu_t)); 
    BleRevMain_send_Cmd((uint8_t *)&Ble_enrollnfc_ack_send.dataLen, Ble_enrollnfc_ack_send.dataLen);
}

/**
 * @brief NFC录入的超时上报
 *
 * @param [in] xTimer
 *
 * @note
 */
static void Add_Nfc_Timeout_Callback(TimerHandle_stu_t xTimer)
{
    nfcadd_timeout_Timer = NULL;
    Ble_enroll_nfc_ack_stu_t Ble_enrollnfc_ack = {0};

    Ble_enrollnfc_ack.result = NFC_ENROLL_TIMEOUT;
    Ble_enrollnfc_ack.user_id = 0;//TODO:是否使用实际的id
    //取消添加nfc，有添加nfc失败的声音提示
    //退出nfc添加
    Menu_Exit_Managemode();
    FunBle_Enroll_Nfc_Notify(&Ble_enrollnfc_ack);
    FUNC_BLE_LOG_D("Add_Nfc_Timeout_Callback");
}

/**
 * @brief NFC添加成功失败,删除定时器   // 0 - 成功 , 1 - 失败, 2 - 卡片已存在
 *
 * @param [in] xTimer
 *
 * @note
 */
static void Del_Nfcaddtimeout_timer(void)
{
    if( nfcadd_timeout_Timer != NULL )
    {
        OSAL_TimerDelete(nfcadd_timeout_Timer);
        nfcadd_timeout_Timer = NULL;
        FUNC_BLE_LOG_D("Del nfcadd_timeout_Timer");
    }
}

/**
 * @brief 通用上报
 *
 *
 * @note
 */
static void FuncBle_general_send_Handle(uint16_t vts, uint16_t cmd, uint8_t payloadLen, uint8_t *payload)
{
    BleAckPacket_stu_t General_send = {0};
    uint8_t ackBuffLen = 0; 
    uint16_t vts_temp = 0;
    uint16_t ver = BLE_MESSAGE_VER;
    uint16_t type = BLE_CON;
    uint16_t cmd_temp = cmd;

    Lock_seq++;
    if (Lock_seq >= 0x03FF)
    {
        Lock_seq = 0;
    }
    ackBuffLen = payloadLen;
    General_send.dataLen = ackBuffLen + 12;
    General_send.dst_addr = APP;
    General_send.src_addr = LKMD;
    General_send.random_code = random_code_global; 

    if(vts == 0)
    {
        vts_temp =  (ver << 12) | (type << 10) | Lock_seq;
        FUNC_BLE_LOG_D("ver:%d",ver);
        FUNC_BLE_LOG_D("type:%d",type);
        FUNC_BLE_LOG_D("Lock_seq:%d",Lock_seq);
        FUNC_BLE_LOG_D("vts_temp:%04x",vts_temp);       
    }
    else
    {
        vts_temp = vts;
    }
    General_send.Payload.vts = vts_temp;
    General_send.Payload.cmd = cmd_temp;
    memcpy(General_send.Payload.dataBuf, payload, ackBuffLen);

    BleRevMain_send_Cmd((uint8_t *)&General_send.dataLen, General_send.dataLen);
}

/**
 * @brief 密钥类型转换函数
 * 
 * @param [in] type 密钥类型
 * @param [in] flag SET：BLE协议转为存储类型  RESET：存储类型转为BLE协议
 * 
 * @note 
 */
static uint8_t ble_codeType_conversion(uint8_t type, FlagStatus flag)
{
    if(flag == SET)
	{
		switch (type)
		{
		case UNLOCK_PWD: 
			return USERS_TYPE_PWD;
		case UNLOCK_FINGER:
			return USERS_TYPE_FPT;
		case UNLOCK_CARD:
			return USERS_TYPE_CARD;
        // case UNLOCK_TEMPORARY_PWD: 
		// 	return USERS_TYPE_TEMPORARY_PWD; 
        case UNLOCK_ROMOTE: 
                return USERS_TYPE_BLE; 
        case UNLOCK_TEMPORARY_PWD: 
            return USERS_TYPE_PLOY_PWD; 
		case UNLOCK_ADMIN_PWD:
			return USERS_TYPE_ADMIN_PWD;  
		default:
			return UNLOCK_UNKNOWN;
		}
	}
	else
	{
		switch (type)
		{
		case USERS_TYPE_PWD:
			return UNLOCK_PWD;
		case USERS_TYPE_FPT:
			return UNLOCK_FINGER;
		case USERS_TYPE_CARD:
			return UNLOCK_CARD;
        case USERS_TYPE_TEMPORARY_PWD:
			return UNLOCK_TEMPORARY_PWD;// 
        case USERS_TYPE_BLE:
                return UNLOCK_ROMOTE; 
        case USERS_TYPE_PLOY_PWD:
            return UNLOCK_TEMPORARY_PWD; // UNLOCK_PERIOD_PWD TODO: 策略密码(APP的访客密码)是否也算周期密码  还是临时密码?
		case USERS_TYPE_ADMIN_PWD:
			return UNLOCK_ADMIN_PWD;  
        case USERS_TYPE_OPEN_KEY:
		 	return UNLOCK_INDOOR;
		default:
			return UNLOCK_UNKNOWN;
		}
	}
}
/**
 * @brief 锁操作上报: 上报开锁事件
 *
 *
 * @note
 */ 
static void Ble_unlock_record_report(EventRecord_stu_t *EventRecord)
{
    Ble_report_unlock_event_stu_t BleRecord = {0};
    uint8_t offset_id = 0;
    uint8_t unlock_type = 0;

    BleRecord.local_timestamp = EventRecord->timestamp;//utc 还是本地时间
    BleRecord.event_id =  g_event_id++;//TODO: 是否要存到flash
    if(g_event_id > 99999)
    {
        g_event_id = 10000;
    }
    unlock_type = ble_codeType_conversion(EventRecord->eventSource, RESET);
    BleRecord.unlock_type = unlock_type;
    if(unlock_type == UNLOCK_FINGER)
    {
        offset_id = 51;
    }
    else if(unlock_type == UNLOCK_CARD)
    {
        offset_id = 101;
    }
    BleRecord.key_id = EventRecord->userID + offset_id;
    
    BleRecord.hijack_flag = 2;//不支持劫持报警, 2:无法判断
    BleRecord.unlocker_alias = 0;//开锁者备注，若不存在，填一字节'\0';
    BleRecord.unlocker_id = 0; //[可选]开锁者 ID,字符串，要求带'\0'
  
    FUNC_BLE_LOG_D("timestamp:%u event_id:%d key_id:%d unlock_type:%d", BleRecord.local_timestamp, BleRecord.event_id, BleRecord.key_id, BleRecord.unlock_type);
    FuncBle_general_send_Handle(0, OSAL_SWAP16(BLE_REPORT_UNLOCK_EVENT), sizeof(Ble_report_unlock_event_stu_t), (uint8_t *)&BleRecord.local_timestamp);
}

/**
 * @brief 锁操作上报: 上报关锁事件
 *
 *
 * @note
 */ 
static void Ble_locked_record_report(EventRecord_stu_t *EventRecord)
{
    Ble_report_locked_event_stu_t BleRecord = {0};
    //uint8_t locked_type = 0;

    BleRecord.local_timestamp = EventRecord->timestamp;
    BleRecord.event_id =  g_event_id++;//TODO: 是否要存到flash
    if(g_event_id > 99999)
    {
        g_event_id = 10000;
    }
    BleRecord.lock_type = EventRecord->eventSource;

    FUNC_BLE_LOG_D("timestamp:%u event_id:%d lock_type:%d", BleRecord.local_timestamp, BleRecord.event_id, BleRecord.lock_type);
    FuncBle_general_send_Handle(0, OSAL_SWAP16(BLE_REPORT_LOCK_EVENT), sizeof(Ble_report_locked_event_stu_t), (uint8_t *)&BleRecord.local_timestamp);
}

/**
 * @brief 删除钥匙通知事件(0x8056)
 *
 *
 * @note
 */ 
static void Ble_delkey_record_report(EventRecord_stu_t *EventRecord)
{
    Ble_report_delkey_event_stu_t BleRecord = {0};
    uint8_t offset_id = 0;
    uint8_t type = 0;

    BleRecord.local_timestamp = EventRecord->timestamp;
    BleRecord.event_id =  g_event_id++;
    if(g_event_id > 99999)
    {
        g_event_id = 10000;
    }
    type = ble_codeType_conversion(EventRecord->eventSource, RESET);
    BleRecord.type = type;
    if(type == UNLOCK_FINGER)
    {
        offset_id = 51;
    }
    else if(type == UNLOCK_CARD)
    {
        offset_id = 101;
    }
    BleRecord.key_id = EventRecord->userID + offset_id;
    BleRecord.unlocker_id = 0; //[可选]开锁者 ID,字符串，要求带'\0'
    FUNC_BLE_LOG_D("del timestamp:%u event_id:%d key_id:%d type:%d", BleRecord.local_timestamp, BleRecord.event_id, BleRecord.key_id, BleRecord.type);
    FuncBle_general_send_Handle(0, OSAL_SWAP16(BLE_REPORT_DEL_KEY_EVENT), sizeof(Ble_report_delkey_event_stu_t), (uint8_t *)&BleRecord.local_timestamp);
}

/**
 * @brief 添加钥匙通知事件(0x8055)
 *
 *
 * @note
 */ 
static void Ble_addkey_record_report(EventRecord_stu_t *EventRecord)
{
    Ble_report_addkey_event_stu_t BleRecord = {0};
    uint8_t offset_id = 0;
    uint8_t type = 0;

    BleRecord.local_timestamp = EventRecord->timestamp;
    BleRecord.event_id =  g_event_id++;
    if(g_event_id > 99999)
    {
        g_event_id = 10000;
    }
    type = ble_codeType_conversion(EventRecord->eventSource, RESET);
    BleRecord.type = type;
    if(type == UNLOCK_FINGER)
    {
        offset_id = 51;
    }
    else if(type == UNLOCK_CARD)
    {
        offset_id = 101;
    }
    BleRecord.key_id = EventRecord->userID + offset_id;
    BleRecord.unlocker_id = 0; //[可选]开锁者 ID,字符串，要求带'\0'
    BleRecord.start_ts = 0;//TODO: 访客密码才需要？
    BleRecord.end_ts = 0;
    FUNC_BLE_LOG_D("add timestamp:%u event_id:%d key_id:%d type:%d", BleRecord.local_timestamp, BleRecord.event_id, BleRecord.key_id, BleRecord.type);
    FuncBle_general_send_Handle(0, OSAL_SWAP16(BLE_REPORT_ADD_KEY_EVENT), sizeof(Ble_report_addkey_event_stu_t), (uint8_t *)&BleRecord.local_timestamp);
}
/************************************ 锁主动发给APP的指令,收到APP的回复 ************************************/
/**
 * @brief 同步网络时间(0x9040)
 *
 *
 * @note
 */
static void FunBle_GetUtcTime(int8_t len, Ble_genaral_rev_t *Data)
{
    Ble_GetUtcTime_stu_t *getutctime_recv = Data;
    uint32_t utctime = 0;
    int16_t timezone = 0; 
    uint8_t curtime[6] = {0};
    FUNC_BLE_LOG_D("len:%d",len);

    utctime = getutctime_recv->utc_time;
    timezone = getutctime_recv->time_zone; //TODO: 是否要保存到nv
    if(OSAL_TimeSet(&utctime, T_UTC) == ERROR)
    {
        FUNC_BLE_LOG_W("FunBle_GetUtcTime set failed");
    }
    OSAL_TimeGet(curtime, T_TIME);
    //FUNC_BLE_LOG_D("cur time :%d,%d,%d,%d,%d,%d\r\n", curTime[0], curTime[1], curTime[2], curTime[3], curTime[4], curTime[5]);
    FUNC_BLE_LOG_HEX("curtime:", curtime, sizeof(curtime));
}

/**
 * @brief 接收APP发送的数据处理
 *
 * @param [in] len
 * @param [in] pdata
 *
 * @note
 */
static uint8_t BleRevMain_ReceiveBleCmd(uint8_t len, uint8_t *pData)
{
    uint8_t res = 0;
    uint32_t cmd = 0;
    static uint8_t bind_flag = 0;
    cmd = pData[2];
    cmd = (cmd << 8) | pData[3];

    FUNC_BLE_LOG_I("cmd:0x%x , len:%d", cmd, len);
    FUNC_BLE_LOG_HEX("BleRevMain data:", pData, len);
    switch (cmd)
    {
        
    case BLE_GET_RAND_CODE:
    {
        len = 4;
      // FuncBle_get_randcode(len, pData);
      FuncBle_get_randcode(len, (Ble_genaral_rev_t *)pData);
    }
    break;


    case BLE_DEVICE_BIND:
    {
        //if (bind_flag == 0)
        {
            FuncBle_Bind(len, pData);
            bind_flag = 1;
        }
    }
    break;

    case BLE_GET_LOCK_ALL_ATTR:
    {
       //if(bind_flag == 1)
       //{
            len = 4;
            FuncBle_Get_All_Attr(len, pData);
            bind_flag = 0;
       //}
       
    }
    break;

    case BLE_KEY_CHECK:
    {
        len = 12;
        FuncBle_KeyCheck(len, pData);
    }
    break; 

    case BLE_GET_PRODUCT_INFO:
    {
        len = 4;
        FuncBle_Get_Product_Info(len, pData);

        if (getutctime_Timer == NULL)
        {
            getutctime_Timer = OSAL_TimerCreate(Send_Getutctime_cmd_Callback, GET_UTC_TIME_TIME, RESET);
            FUNC_NB_LOG_D("Create getutctime_Timer 1");
        }
    }
    break;


    case BLE_UNLOCK:
    {
        len = 4;
        FuncBle_Unlock(len, pData);

    }
    break; // 

    case BLE_LOCKED:
    {
        len = 4;
        FuncBle_Locked(len, pData);

    }
    break;

    case BLE_GET_LOCK_STATUS:
    {
        len = 4;
        FuncBle_Get_Lock_Status(len, pData);
        if (getutctime_Timer == NULL)
        {
            getutctime_Timer = OSAL_TimerCreate(Send_Getutctime_cmd_Callback, GET_UTC_TIME_TIME, RESET);
            FUNC_NB_LOG_D("Create getutctime_Timer 2");
        }
    }
    break; 

    case BLE_SET_ADMIN_PWD:
    {
        len = 36;
        FuncBle_Set_Admin_Pwd(len, pData);
    }
    break; 

    case BLE_CHANGE_ADMIN_PWD:
    {
        len = 44; // 
        FuncBle_Change_Admin_Pwd(len, pData);
    }
    break; 

    case BLE_ADD_LOCAL_PWD:
    {
        len = 50; //结构体
        FuncBle_Add_Local_Pwd(len, pData);//TODO: pData只传有效数据进入，vts和cmd通过参数传入 ?
    }
    break;

    case BLE_GET_PWD_INFO:
    {
        FuncBle_Get_Pwd_Info(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_SET_VOLUME:
    {
        len = 6;
        FuncBle_Set_Volume(len, pData);
    }
    break; 

    case BLE_DEL_LOCAL_PWD:
    {
        FuncBle_Del_Local_Pwd(sizeof(Ble_keyDel_stu_t), (Ble_keyDel_stu_t *)pData);
    }
    break;

    case BLE_DEL_FINGER:
    {
        FuncBle_Del_Finger(sizeof(Ble_FingerDel_stu_t), (Ble_FingerDel_stu_t *)pData);
    }
    break;

    case BLE_GET_UTC_TIME:
    {
        FunBle_GetUtcTime(sizeof(Ble_GetUtcTime_stu_t), (Ble_GetUtcTime_stu_t *)pData);
    }
    break;

    case BLE_ADD_FINGER:
    {
        FuncBle_Add_Finger(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_CANCEL_ADD_FINGER:
    {
        FuncBle_Cancel_Add_Finger(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_ADD_NFC:
    {
        FuncBle_Add_Nfc(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_CANCEL_ADD_NFC:
    {
        FuncBle_Cancel_Add_Nfc(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_GET_VOLUME:
    {
        FuncBle_Get_Volume(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_GET_POWR_VALUE:
    {
        FuncBle_Get_Power_Value(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    case BLE_SETTING_AUTO_LOCK_TIME:
    {
        FuncBle_Set_AutoLock_Time(sizeof(Ble_Setting_AutoLock_Time_stu_t), (Ble_Setting_AutoLock_Time_stu_t *)pData);
    }
    break;

    case BLE_GET_AUTO_LOCK_TIME:
    {
        FuncBle_Get_AutoLock_Time(sizeof(Ble_genaral_rev_t), (Ble_genaral_rev_t *)pData);
    }
    break;

    default: 
    {
    }
    break;
    }

    return res;
}

/**
 * @brief  BLE组件消息回调
 * @note
 * @param  *msg 消息指针
 * @param  len 消息长度
 * @return void
 */
static void RevMainBleCb(void *msg, uint16_t len)
{
    BlePublishMsg_t *ble = (BlePublishMsg_t *)msg;
    uint8_t bleMac[6];
    FUNC_BLE_LOG_D("RevMainBleCb type:%d \r\n", ble->type);
    switch (ble->type)
    {
    case PUBLISH_APP_CMD:
       // SYS_CALL(Set_BleConnectStatust, 1);
       //FUNC_BLE_LOG_HEX("RevMainBleCb:", ble->pData, ble->len);

        BleRevMain_ReceiveBleCmd(ble->len, ble->pData);
        break;

    case PUBLISH_BLE_MAC: //TODO: 80B0的地址从这里获取
        OSAL_NvRead(SYS_OFFSET(bleMacAddr), bleMac, 6);
        if (memcmp(bleMac, ble->pData, 6) != 0) //不同才写入
        {
            OSAL_NvWrite(SYS_OFFSET(bleMacAddr), ble->pData, 6);
        }
        FUNC_BLE_LOG_HEX("mac address:", ble->pData, 6);

        break;

    case PUBLISH_BLE_STATUS:
        if (ble->pData[0])
        {
            // SYS_CALL(Set_BleConnectStatust, 1);
            FUNC_BLE_LOG_D("ble status is connected\r\n");
            //bleConnectSta = 1;
            Led_Set("LED_LOGO_W", LED_ON, 0, 0);
        }
        else
        {
            //SYS_CALL(Set_BleConnectStatust, 0);
            //bleConnectSta = 0;
            FUNC_BLE_LOG_D("ble status is disconnect\r\n");
            Led_Set("LED_LOGO_W", LED_OFF, 0, 0);
        }
        break;

    case PUBLISH_HEART_BEAT:
        // 刷新定时器
        FUNC_BLE_LOG_D("Heartbeat event");
        break;

    default:
        break;
    }

    OSAL_UpdateSleepTime(8000, 1);//TODO:时间待定 15000
}
/**
 * @brief BLE休眠回调函数
 * @note
 * @param
 * @retval ErrorStatus
 */
static ErrorStatus Ble_sleep_cb(void)
{
    FUNC_BLE_LOG_I("ble_main sleep\r\n");
    Menu_SetAppAddCardFlag(RESET);
    //TODO: 绑定过程的2分钟超时定时器以内不休眠
    // if (bleActiveTimer != NULL) //激活模式1分钟不休眠
    // {
    //     return ERROR;
    // }
    //else
    //{
        return SUCCESS;
    //}
}
/**
 * @brief  BLE APP启动函数
 * @note
 *
 * @param  wake_id：唤醒ID（组件ID），0XFF表示上电唤醒
 * @param  wake_param：唤醒参数
 */
static void BLE_Main(uint32_t wake_id, uint32_t wake_param)
{
    FUNC_BLE_LOG_I("ble_main wake_id:%d, wake_param:%d\r\n", wake_id, wake_param);
    //上电唤醒：创建APP，订阅消息
    AppHandle_t app_handle = OSAL_AppCreate("BLE_Main", Ble_sleep_cb);
    OSAL_MessageSubscribe(app_handle, COMP_BLE, RevMainBleCb);
    OSAL_MessageSubscribe(app_handle, COMP_FINGER, Finger_MsgCb);
    SYS_API(FunBle_Enroll_Nfc_Notify);
    SYS_API(Del_Nfcaddtimeout_timer);
    SYS_API(Ble_unlock_record_report);
    SYS_API(Ble_locked_record_report);
    SYS_API(Ble_delkey_record_report);
    SYS_API(Ble_addkey_record_report);
}
APP_INIT_EXPORT(BLE_Main);
